//
//  ANMineShoppingCartController.m
//  WeiYiMei
//
//  Created by 李叶夫 on 2019/4/14.
//  Copyright © 2019年 liyefu. All rights reserved.
//

#import "ANMineShoppingCartController.h"
#import "MineOrderCell.h"
#import "ShoppingCartPayView.h"
#import "ShoppingCartEntity.h"
#import "ANOrderPayController.h"

@interface ANMineShoppingCartController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) ShoppingCartPayView *payView;

@property (nonatomic, strong) NSMutableArray<ShoppingCartEntity *> *dataSource;

@property (nonatomic, strong) ShoppingCartEntity *currentSelectEntity;

@property (nonatomic) int pageNo;

@end

@implementation ANMineShoppingCartController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"购物车";
    self.pageNo = 1;
    self.dataSource = @[].mutableCopy;
    
    [self requestData];
}

- (void)setupSubViews
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.backgroundColor = kColorF2F2F2;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 10, 0);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[MineOrderCell class] forCellReuseIdentifier:@"MineOrderCell"];
    
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    WeakSelf
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pageNo = 1;
        [weakSelf.payView clearData];
        weakSelf.currentSelectEntity = nil;
        [weakSelf requestData];
    }];
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.pageNo++;
        [weakSelf requestData];
    }];
    
    self.payView = [[ShoppingCartPayView alloc] init];
    [self.view addSubview:self.payView];
    self.payView.payHandler = ^{
        [weakSelf buy];
    };
}

- (void)setupConstraints
{
    [self.payView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.left.right.equalTo(self.view);
        make.height.equalTo(@(kWidth(54)+kiPhoneXInsetBottom));
    }];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.bottom.equalTo(self.payView.mas_top);
    }];
    
    
}

- (void)buy
{
    if (self.currentSelectEntity) {
        ANOrderPayController *vc = [[ANOrderPayController alloc] init];
        vc.shoppingCartId = self.currentSelectEntity.shoppingCartId;
        vc.goodsNum = self.currentSelectEntity.purchaseNum.intValue;
        vc.type = ANOrderPayControllerTypeShoppingCart;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else {
        [MBProgressHUD showError:@"请选择商品"];
    }
}

- (void)requestData
{
    NSDictionary *body = @{
                           @"memberId":UserUtils.shared.vipId,
                           @"pageNo":@(self.pageNo),
                           @"pageSize":@20
                           };
    [URLManager.shareManager getUrlStr:Api_Get_ShoppingCart parameters:body entityClass:[ShoppingCartListEntity class] success:^(NSURLResponse * _Nonnull response, BaseEntity * _Nullable baseEntity, NSDictionary * _Nullable otherResponse) {
        
        if (baseEntity) {
            if (baseEntity.code.intValue == 200) {
                ShoppingCartListEntity *data = baseEntity.data;
                if (self.pageNo == 1) {
                    [self.dataSource removeAllObjects];
                    [self.tableView.mj_header endRefreshing];
                    [self.tableView.mj_footer resetNoMoreData];
                    if (data.data.count < 20) {
                        self.tableView.mj_footer.alpha = 0;
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                }
                else {
                    if (data.data.count < 20) {
                        [self.tableView.mj_footer endRefreshingWithNoMoreData];
                    }
                    else {
                        [self.tableView.mj_footer endRefreshing];
                    }
                }
                [self.dataSource addObjectsFromArray:data.data];
                [self.tableView reloadData];
            }
            else {
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer endRefreshing];
            }
        }
        else {
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer endRefreshing];
        }
        
        
        
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)deleteRequest:(NSIndexPath *)indexPath
{
    NSDictionary *body = @{
                           @"id":self.dataSource[indexPath.row].shoppingCartId
                           };
    [MBProgressHUD showActivityMessage:nil];
    [URLManager.shareManager postUrlStr:Api_Delete_ShoppingCart parameters:body success:^(NSURLResponse * _Nonnull response, id  _Nullable responseObj, NSDictionary * _Nullable otherResponse) {
        [MBProgressHUD hideHUD];
        if (responseObj) {
            if ([responseObj[@"code"] intValue] == 200) {
                [MBProgressHUD showMessage:responseObj[@"message"]];
                [self.dataSource removeObjectAtIndex:indexPath.row];
                [self.tableView reloadData];
            }
            else {
                [MBProgressHUD showMessage:responseObj[@"message"]];
            }
        }
    } failure:^(NSURLResponse * _Nullable response, NSError * _Nonnull error) {
        [MBProgressHUD hideHUD];
    }];
}

- (void)updatePayView:(ShoppingCartEntity *)entity
{
    if (self.currentSelectEntity && self.currentSelectEntity != entity) {
        self.currentSelectEntity.isSelect = @(NO);
    }
    entity.isSelect = @(!entity.isSelect.boolValue);
    if (!entity.isSelect.boolValue) {
        self.currentSelectEntity = nil;
        [self.payView clearData];
    }
    else {
        self.currentSelectEntity = entity;
        NSString *p;
        if (UserUtils.shared.isMembership) {
            float price = entity.memberPrice.floatValue * entity.purchaseNum.intValue;
            p = [NSString stringWithFormat:@"%.2f",price];
        }
        else {
            float price = entity.price.floatValue * entity.purchaseNum.intValue;
            p = [NSString stringWithFormat:@"%.2f",price];
        }
        self.payView.totalNum = entity.purchaseNum;
        self.payView.totalPrice = p;
    }
    [self.tableView reloadData];
}

- (void)updatePayViewForAddOrDelete:(ShoppingCartEntity *)entity
{
    NSString *p;
    if (UserUtils.shared.isMembership) {
        float price = entity.memberPrice.floatValue * entity.purchaseNum.intValue;
        p = [NSString stringWithFormat:@"%.2f",price];
    }
    else {
        float price = entity.price.floatValue * entity.purchaseNum.intValue;
        p = [NSString stringWithFormat:@"%.2f",price];
    }
    self.payView.totalNum = entity.purchaseNum;
    self.payView.totalPrice = p;
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MineOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MineOrderCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.canSelect = YES;
    cell.entity = self.dataSource[indexPath.row];
    WeakSelf
    cell.selectHandler = ^(int num) {
        ShoppingCartEntity *entity = self.dataSource[indexPath.row];
        entity.purchaseNum = [NSString stringWithFormat:@"%d",num];
        [self updatePayView:entity];
    };
    cell.addOrDeleteHandler = ^(int num) {
        ShoppingCartEntity *entity = self.dataSource[indexPath.row];
        entity.purchaseNum = [NSString stringWithFormat:@"%d",num];
        if (entity == self.currentSelectEntity) {
            [weakSelf updatePayViewForAddOrDelete:entity];
        }
        // 调用修改数量的接口
        
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kWidth(188);
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self deleteRequest:indexPath];
}


- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
